package com.msblearn.JVM.C02_ClassLoader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 热部署，实现打破双亲委派机制。
 * 继承ClassLoader:兵重写loadClass();
 */
public class T06_ClassReadloading {

    private static class MyLoader extends ClassLoader{
        @Override
        public Class<?> loadClass(String name) throws ClassNotFoundException {

            File f = new File("E:/2020/java基础/JVM/target/classes/" + name.replace(".", "/").concat(".class"));
//            System.out.println(f.exists());
            if(!f.exists()) return super.loadClass(name);

            try {

                InputStream is = new FileInputStream(f);

                byte[] b = new byte[is.available()];
                is.read(b);
                return defineClass(name, b, 0, b.length);
            } catch (IOException e) {
                e.printStackTrace();
            }

            return super.loadClass(name);
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        MyLoader m = new MyLoader();
        Class clazz = m.loadClass("com.msblearn.JVM.HelloJVM");
        System.out.println(clazz.hashCode());
        m = new MyLoader();
        Class clazzNew = m.loadClass("com.msblearn.JVM.HelloJVM");

        System.out.println(clazzNew.hashCode());
        System.out.println(clazz == clazzNew);
    }
}
